package com.wpr.shop.configure.filter;

import com.wpr.shop.utils.GzipUtils;
import com.wpr.shop.utils.servlet.MyHttpResponseWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.invoke.MethodHandles;

/**
 * describe:
 *
 * @author zhanglisheng
 * @date 2018/10/25
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "wrappingFilter")
public class WrappingFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String apiGzip = req.getHeader("Api-Gzip");
        String ae = req.getHeader("Accept-Encoding");
        String uid = req.getHeader("uid");
        String from = req.getHeader("Request-From");
        String requestURL = req.getRequestURL().toString();
        String queryArgs = req.getQueryString();

        LOGGER.info("header paramters Accept-Encoding:{} Api-Gzip:{} UID:{} RequestURL:{},FROM:{}",ae,apiGzip,uid,requestURL + "?" + queryArgs,from);

        MyHttpResponseWrapper wrapperResponse = new MyHttpResponseWrapper(resp);
        chain.doFilter(request, wrapperResponse);

        String content = wrapperResponse.getContent();
        response.setContentLength(-1);
        if ("1".equals(apiGzip)) {
            resp.setContentType("application/gzip;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.addHeader("Content-Encoding", "gzip");

            byte[] gzipBytes = GzipUtils.toGzipBytes(content); //下行数据压缩
            ServletOutputStream output = resp.getOutputStream();
            resp.setContentLength(gzipBytes.length);
            output.write(gzipBytes);
            output.flush();
        } else {
            response.getWriter().write(content);
        }
    }

    @Override
    public void destroy() {

    }
}
